//
//  DbDao.m
//  SqliteTest
//
//  Created by foxwang on 12-4-9.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "DbDao.h"
#import "DbFileManager.h"

#import "FMDatabase.h"
#import "FMDatabaseAdditions.h"
#import "FMDatabasePool.h"
#import "FMDatabaseQueue.h"
#import "CityArea.h"
#import "LicensePlate.h"
static DbDao *gSharedInstance = nil;

@implementation DbDao
@synthesize dbFile;
@synthesize dbQueue;

+(DbDao *)sharedInstance
{
    @synchronized(self)
    {
        if (gSharedInstance == nil)
			gSharedInstance = [[DbDao alloc] init];
    }
    return gSharedInstance;	
}

- (void)dealloc
{
    
    self.dbQueue = nil;
  
}

- (id)init
{
    
    self = [super init];
    if (self)
    {
        self.dbFile = [DbFileManager dbFilePath];
        self.dbQueue = [FMDatabaseQueue databaseQueueWithPath:self.dbFile];
        
        
    }
    return  self;
}


- (CityArea *)rsToClassify:(FMResultSet*)rs
{
    CityArea *cityArea = [[CityArea alloc] init];
    cityArea.a_id = [rs intForColumn:@"a_id"];
    cityArea.a_name = [rs stringForColumn:@"a_name"];
    cityArea.a_parent_id = [rs intForColumn:@"a_parent_id"];
    cityArea.a_level = [rs intForColumn:@"a_level"];
    cityArea.a_relation = [rs stringForColumn:@"a_relation"];
    cityArea.a_description = [rs stringForColumn:@"a_description"];
    cityArea.a_sort = [rs intForColumn:@"a_sort"];
    cityArea.a_lat = [rs doubleForColumn:@"a_lat"];
    cityArea.a_lng = [rs doubleForColumn:@"a_lng"];
    cityArea.a_pinyin = [rs stringForColumn:@"a_pinyin"];
    return cityArea;
}
- (LicensePlate *)rsToLicensePlateClassify:(FMResultSet*)rs
{
    LicensePlate *licensePlate = [[LicensePlate alloc] init];
    licensePlate.a_id = [rs intForColumn:@"ID"];
    licensePlate.a_name = [rs stringForColumn:@"NAME"];
    return licensePlate;
}

- (NSArray *)getCityArea:(NSString *)sqlQuery
{
    __block NSMutableArray *users = [[NSMutableArray alloc] init];  
    [self.dbQueue inDatabase:^(FMDatabase *db)   {
        [db open];
        FMResultSet *rs = [db executeQuery:sqlQuery];
        while ([rs next])
        {
            [users addObject:[self rsToClassify :rs]];
        }
        [db close];
    }];
    return users;
}
- (NSArray *)getLicensePlate:(NSString *)sqlQuery{
    __block NSMutableArray *users = [[NSMutableArray alloc] init];
    [self.dbQueue inDatabase:^(FMDatabase *db)   {
        [db open];
        FMResultSet *rs = [db executeQuery:sqlQuery];
        while ([rs next])
        {
            [users addObject:[self rsToLicensePlateClassify :rs]];
        }
        [db close];
    }];
    return users;
}
@end
